package com.cyz.common.security;

import com.alibaba.fastjson.JSON;
import com.cyz.common.enums.MyEnums;
import com.cyz.common.utils.R;
import com.cyz.common.utils.WebUtils;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义认证失败处理器
 */
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {

    R r = null;

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException){
        if(authException instanceof BadCredentialsException){
            r = R.error(MyEnums.LOGIN_ERROR.getCode(),authException.getMessage());
        }else if(authException instanceof InsufficientAuthenticationException){
            r = R.error(MyEnums.NEED_LOGIN.getCode(),authException.getMessage());
        }else{
            r = R.error(MyEnums.SYSTEM_ERROR.getCode(),"认证失败");
        }
        WebUtils.renderString(response, JSON.toJSONString(r));
    }
}
